package com.zzb.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.zzb.ucenter.mapper.XcMenuMapper;
import com.zzb.ucenter.model.dto.AuthParamsDto;
import com.zzb.ucenter.model.dto.XcUserExt;
import com.zzb.ucenter.model.po.XcMenu;
import com.zzb.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author zzb
 * @Date 2024/6/25 16:54
 * @Version 1.0
 * @description
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private XcMenuMapper xcMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(username, AuthParamsDto.class);
        } catch (Exception exception) {
            log.error("认证要求不符合项目要求:{}", exception.getMessage());
            return null;
        }
        //获取登录类型
        String authType = authParamsDto.getAuthType();
        //获取指定的bean
        AuthService authService = applicationContext.getBean(authType + "_authservice", AuthService.class);
        //执行认证
        XcUserExt userExt = authService.execute(authParamsDto);
        return getUserPrincipal(userExt);
    }

    /**
     * 查询用户信息
     * @param userExt
     * @return
     */
    private UserDetails getUserPrincipal(XcUserExt userExt) {
        //查询用户权限
        List<XcMenu> menus = xcMenuMapper.selectPermissionByUserId(userExt.getId());
        String[] authorities = new String[0];
        if (menus != null) {
            authorities = menus.stream().map(XcMenu::getCode).toArray(String[]::new);
        }
        //获取密码
        String password = userExt.getPassword();
        //为了安全在令牌中不放密码
        userExt.setPassword(null);
        //讲user对象转为json
        String userJson = JSON.toJSONString(userExt);
        //创建userDetail对象
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }
}
